package com.guoguo.utils;

import com.guoguo.entity.Task;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Administrator on 2017/8/17 0017.
 */
public class QuartzUtils {
    private final static String JOB_GROUP_NAME = "QUARTZ_JOBGROUP_NAME";//任务组
    private final static String TRIGGER_GROUP_NAME = "QUARTZ_TRIGGERGROUP_NAME";//触发器组
    private static Logger log = LoggerFactory.getLogger(QuartzUtils.class);//日志


    private static Scheduler sche;


    /**
     * 添加任务的方法
     *
     * @param task
     * @throws SchedulerException
     */
    public static void addJob(Task task) throws SchedulerException {
        log.info("==================initialization=================");

        init();

        log.info("===================initialize finshed===================");

        log.info("==============add the Job to Scheduler==================");

        JobDetail jobDetail = JobBuilder.newJob(ClazzUtils.getEntityClass(task.getClassName())).withIdentity(task.getTaskName(), task.getTaskGroup())
                .usingJobData("className", task.getClassName()).usingJobData("methodName", task.getMethodName()).build();

        // 表达式调度构建器（可判断创建SimpleScheduleBuilder）
        CronScheduleBuilder scheduleBuilder = null;
        if (CronExpression.isValidExpression(task.getCronExpression())) {
            scheduleBuilder = CronScheduleBuilder.cronSchedule(task.getCronExpression());
            // 按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(task.getTaskName(), task.getTaskGroup()).withSchedule(scheduleBuilder).build();

            sche.scheduleJob(jobDetail, trigger);
            sche.start();
        } else {
            addJob(task.getTaskName(), task.getTaskGroup(), ClazzUtils.getEntityClass(task.getClassName()), Integer.parseInt(task.getCronExpression()));
        }
    }

    /**
     * 添加任务的方法
     *
     * @param jobName     任务名
     * @param triggerName 触发器名
     * @param jobClass    执行任务的类
     * @param seconds     间隔时间
     * @throws SchedulerException
     */
    public static void addJob(String jobName, String triggerName, Class<? extends Job> jobClass, int seconds) throws SchedulerException {
        log.info("==================initialization=================");

        init();

        log.info("===================initialize finshed===================");

        log.info("==============add the Job to Scheduler==================");

        //用于描叙Job实现类及其他的一些静态信息，构建一个作业实例
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, JOB_GROUP_NAME).build();


        //构建一个触发器，规定触发的规则
        Trigger trigger = TriggerBuilder.newTrigger()//创建一个新的TriggerBuilder来规范一个触发器
                .withIdentity(triggerName, TRIGGER_GROUP_NAME)//给触发器起一个名字和组名
                .startNow()//立即执行
                .withSchedule(
                        SimpleScheduleBuilder.simpleSchedule()
                                .withIntervalInSeconds(seconds)//时间间隔  单位：秒
                                .repeatForever()//一直执行
                )
                .build();//产生触发器
        //向Scheduler中添加job任务和trigger触发器
        sche.scheduleJob(jobDetail, trigger);

        //启动
        sche.start();
    }

    /**
     * 停止定时器工厂
     *
     * @throws SchedulerException
     */
    public static void removeJob() throws SchedulerException {
        init();
        sche.shutdown();
    }

    /**
     * 初始化参数
     *
     * @throws SchedulerException
     */
    private static void init() throws SchedulerException {
        if (sche == null) {
            //c
            SchedulerFactory sf = new StdSchedulerFactory();

            //通过SchedulerFactory构建Scheduler对象
            sche = sf.getScheduler();
        }
    }
}
